package xj.graph2d.encoder;

import java.awt.Color;
import java.awt.geom.Rectangle2D;
import java.io.BufferedOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.Writer;

import org.apache.batik.dom.GenericDOMImplementation;
import org.apache.batik.svggen.SVGGraphics2D;
import org.w3c.dom.DOMImplementation;

import xj.graph2d.AbstractEncoder;
import xj.graph2d.DrawCanvas;
import xj.graph2d.View;

public class BatikSVGEncoder extends AbstractEncoder {

  public BatikSVGEncoder() {
  }

  public BatikSVGEncoder(String name, String fileExtension,
      String fileDescription, View view) {
    super(name, fileExtension, fileDescription, view);
    transparent = false;
  }

  @Override
  public void encode(String filename, Rectangle2D r) throws IOException {
    if (view != null) {
      DrawCanvas canvas = view.getCanvas();
      if (filename != null && canvas != null && r != null) {
	int mw = (int) view.getMarginWidth();
	int mh = (int) view.getMarginHeight();
	int w = (int) r.getWidth() + 2 * mw;
	int h = (int) r.getHeight() + 2 * mw;
	DOMImplementation domImpl = GenericDOMImplementation
	    .getDOMImplementation();
	org.w3c.dom.Document document = domImpl.createDocument(null, "svg",
	    null);
	SVGGraphics2D svgGenerator = new SVGGraphics2D(document);
	if (!transparent) {
	  Color bg = view.getBackgroundColor();
	  svgGenerator.setColor(bg);
	  svgGenerator.fillRect(0, 0, w, h);
	}
	drawWaterMark(svgGenerator, 0, 0, w, h);

	svgGenerator.translate(-r.getX() + mw, -r.getY() + mh);
	view.paintCanvas(svgGenerator, null, true); // draw all objects
	boolean useCSS = true; // we want to use CSS style attribute
	BufferedOutputStream bos = new BufferedOutputStream(
	    new FileOutputStream(filename));
	Writer out = new OutputStreamWriter(bos, "UTF-8");
	svgGenerator.stream(out, useCSS);
      }
    }
  }

}
